package com.crawler.waf.testconfig;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.crawler.waf.security.authens.WafUserAuthentication;
import com.crawler.waf.security.authens.UserCenterUserDetails;
import com.crawler.waf.security.authentication.WafAuthenticationException;
import com.crawler.waf.security.services.impl.UserCenterUserDetailsService;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class BaseSpringJunit4Config {

	protected MockMvc mockMvc;

	@Autowired
	private WebApplicationContext webApplicationContext;
	
	protected String userId;

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	@Before
	public void setUp(){

		mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

		WafUserAuthentication authentication = this.getPrincipal(this.getUserId());
		
		/**
		 * 把用户信息添加到全局的SecurityContextHolder对象中。
		 */
		SecurityContextHolder.getContext().setAuthentication(authentication);
	}

	protected WafUserAuthentication getPrincipal(String userId) {
		
		UserCenterUserDetailsService userCenterUserDetailsService = new UserCenterUserDetailsService();
		WafUserAuthentication authentication = new WafUserAuthentication(null);
		try {
			UserCenterUserDetails userCenterUserDetails = userCenterUserDetailsService
					.loadUserDetailsByUserId(userId);
			authentication.setDetails(userCenterUserDetails);
		}  catch (RuntimeException ex) {
			throw new WafAuthenticationException("获取用户信息发生异常 " + ex.getMessage(), ex);
		}
		return authentication;
	}
}
